package weibo.tools;

import java.io.*;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

/*
 * HTML模板
 */
public class HTMLtemplate {
	private String templateURL=null;
	private String outURL=null;
	private String str=null;
	
	
	/*
	 * 读取HTML模板文件
	 * param 模板路径,输出目录
	 */
	public HTMLtemplate(String templateURL,String outURL){
		this.templateURL=templateURL;
		this.outURL=outURL;
		
		try {
			this.str = "";
			String tempStr = "";
			
			FileInputStream is = new FileInputStream(this.templateURL);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while ((tempStr = br.readLine()) != null){
				this.str = this.str + tempStr ;
			}  
            is.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			System.out.println("模板文件不存在");
			e.printStackTrace();
		}//读取模块文件
	}
	
	/*
	 * 替换模板文件内容
	 * param json{str1:'str1',str2:'str2'} json格式的内容
	 */
	public boolean replaceTemplate(JSONObject content){
		for (Map.Entry<String, Object> entry : content.entrySet()) {
			String Key=entry.getKey();
			String Value=entry.getValue().toString();
			this.str=this.str.replaceAll("###"+Key+"###", Value);
        }
		File f = new File(this.outURL);
		try {
			OutputStreamWriter writerStream = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
			BufferedWriter fp = new BufferedWriter(writerStream);
			fp.write(this.str);
			fp.close();
			return true;
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			System.out.println("写入文件出现问题");
			e.printStackTrace();
		}
		return false;
	}
	
}
